<?php
use Phalcon\Mvc\View;

class SiteController extends ControllerBase
{

    public function indexAction()
    {
        $this->tag->prependTitle('你创建的站点 - ');
        $this->assets->addCss("/css/split-pane.css");
        $this->assets->addCss("/css/pretty-split-pane.css");
        $this->assets->addCss("/css/admin.css");
        $this->assets->addJs("/js/split-pane.js");
        $this->assets->addJs("/static/site/js/site.js");
        $site = [];
        $rows = MsSite::find(
            [
                "created_uid = '" . $this->auth['id'] . "'",
                "order" => "id DESC",
                "limit" => 10,
            ]
        );

        if ($rows) {
            $rows = $rows->toArray();
            foreach ($rows as $key => $value) {
                $site[] = $value;
            }
        }
        $this->view->setVars(
            [
                'site' => $site,
            ]
        );
    }
    public function createAction($sitename)
    {
        $count = MsSite::count(["created_uid = '" . $this->auth['id'] . "'"]);
        if ($count >= 10) {
            $json = ['code' => 1, 'msg' => '创建站点已达上限'];
        } else {
            $siteid = md5(Common::getMicroTime());

            $msSite               = new MsSite();
            $msSite->name         = $sitename;
            $msSite->md5          = $siteid;
            $msSite->created_uid  = $this->auth['id'];
            $msSite->created_time = time();
            if ($msSite->save() === false) {
                $this->logger->error('站点创建失败 ' . __LINE__); //将错误记录日志，便于今后分析。
                $json = ['code' => 0, 'msg' => '站点创建失败'];
            } else {
                $json = ['code' => 0, 'msg' => null, 'data' => ['name' => $sitename, 'md5' => $siteid]];
                mkdir(BASE_PATH . '/_site/' . $siteid, 0777, true);
                foreach ($this->defaultFolder as $key => $value) {
                    mkdir(BASE_PATH . '/_site/' . $siteid . $value, 0777, true);
                }
            }
        }
        $this->response->setJsonContent($json);
        return $this->response;
    }
    public function publicAction()
    {

    }
    public function deployAction()
    {

    }

    public function previewAction($siteid)
    {
        $path     = $this->request->getQuery('path');
        $filepath = BASE_PATH . '/_site/' . $siteid . '/public/' . $path;
        if (file_exists($filepath)) {
            $file = file_get_contents(BASE_PATH . '/_site/' . $siteid . '/public/' . $path);

            echo Common::replaceAsset($file, '/_site/' . $siteid . '/asset');
            $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
        } else {
            $this->response->setStatusCode(404, 'Not Found');
            return $this->response;
        }
    }
}
